package com.zhejiangzhengyuan.municipal_common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhejiangzhengyuan.municipal_common.entity.*;
import com.zhejiangzhengyuan.municipal_common.entity.dto.OneWaySendCase;
import com.zhejiangzhengyuan.municipal_common.entity.vo.*;
import com.zhejiangzhengyuan.municipal_common.entity.dto.NewCase;
import com.zhejiangzhengyuan.municipal_common.mapper.*;
import com.zhejiangzhengyuan.municipal_common.response.ResponseVo;
import com.zhejiangzhengyuan.municipal_common.service.CaseManagementService;
import com.zhejiangzhengyuan.municipal_common.service.CaseService;
import com.zhejiangzhengyuan.municipal_common.service.CaseWarnEventMappingService;
import com.zhejiangzhengyuan.municipal_common.utils.ConstantUtil;
import com.zhejiangzhengyuan.municipal_common.utils.excelFileUtils.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

import static com.zhejiangzhengyuan.municipal_common.utils.DateFormatUtil.timeFormat;
import static com.zhejiangzhengyuan.municipal_common.utils.excelFileUtils.FileUtil.getFilePo;

/**
 * @author :linju
 * @since on : 2019/11/26
 */
@Service
public class CaseManagementServiceImpl implements CaseManagementService {

  @Autowired private InspectionEventMapper inspectionEventMapper;
  @Autowired private CaseInspectionEventMappingMapper caseInspectionEventMappingMapper;
  @Autowired private CaseManagementMapper caseManagementMapper;
  @Autowired private CaseService caseService;
  @Autowired private OneWayCaseDetails1Mapper oneWayCaseDetails1Mapper;
  @Autowired private OneWayCaseDetails2Mapper oneWayCaseDetails2Mapper;
  @Autowired private CaseMapper caseMapper;
  @Autowired private OneWayCaseMapper oneWayCaseMapper;
  @Autowired private CaseWarnEventMappingService caseWarnEventMappingService;
  @Autowired private DeviceMapper deviceMapper;
  @Autowired private CaseTrackMapper caseTrackMapper;
  @Autowired private PumpStationDataManagementMapper pumpStationDataManagementMapper;
  @Autowired private FileMapper fileMapper;
  @Autowired private WarnEventMapper warnEventMapper;
  @Autowired private InspectionEventFileMappingMapper inspectionEventFileMappingMapper;
  @Autowired private ReceiptMapper receiptMapper;
  @Autowired private UserInfoMapper userInfoMapper;
  @Autowired private CaseIsHandledMapper caseIsHandledMapper;
  @Autowired private RoadGisMapper roadGisMapper;
  @Autowired private BridgeGisMapper bridgeGisMapper;

  private String moduleName = ConstantUtil.MODULE_NAME.WAY;
  private String manholeDepartmentName = "排水抢修组";
  private String wayDepartmentName = "路桥抢修组";

  @Override
  public Page<CaseNoHandle> selectAll(
      Page<CaseNoHandle> page,
      String warnType,
      String dataOrigin,
      String deviceCode,
      String reason,
      String username,
      String startTimestamp,
      String endTimestamp) {
    return this.caseManagementMapper.selectAll(
        page, warnType, dataOrigin, deviceCode, reason, username, startTimestamp, endTimestamp);
  }

  /** 井盖管理新建案件 */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public ResponseVo insertCaseAndWarn(
      NewCase newCase, String module, String caseType, String warnType) throws IOException {
      // 判断上报人是否存在
      if (Objects.isNull(userInfoMapper.selectById(newCase.getReportUserInfoId()))) {
          return ResponseVo.CLIENT_PARAM_ERROR;
      }

      // 新建一个案件
      Case c =
              new Case()
                      .setLocation(newCase.getLocation())
                      .setGrade(newCase.getGrade())
                      .setCaseDescribe(newCase.getCaseDescribe())
                      .setAdvice(newCase.getAdvice());

      WarnEvent warnEvent =
              new WarnEvent()
                      .setReason(newCase.getReason())
                      .setReportUserInfoId(newCase.getReportUserInfoId())
                      .setCreateTime(newCase.getCreateTime())
                      .setRemark(newCase.getRemark())
                      .setLevel(newCase.getGrade())
                      .setDataOrigin("人工上报")
                      .setDeviceId(1L)
                      .setType(warnType)
                      .setSendOrder(true);
      caseService.newCase(c, caseType);
      warnEventMapper.insert(warnEvent);
      //    long wid = warnEventService.insertWarnEvent(module, warnEvent, warnType,
      // manholeDepartmentName);
      // 发送短信
      caseService.insertMessageToDepartment(module, caseType, "领取任务", manholeDepartmentName);
      caseWarnEventMappingService.insertCaseWarnMapping(c.getId(), warnEvent.getId());
      return ResponseVo.successWithData(warnEvent.getId());
  }

  @Override
  public Page<CaseIsHandledVo> selectCaseIsHandledPage(
      Page<CaseIsHandledVo> page,
      String caseType,
      String warnType,
      String dataOrigin,
      String deviceCode,
      String reason,
      String username,
      String startTimestamp,
      String endTimestamp) {
    return caseIsHandledMapper.selectCaseIsHandledPage(
        page,
        caseType,
        warnType,
        dataOrigin,
        deviceCode,
        reason,
        username,
        startTimestamp,
        endTimestamp);
  }

  @Override
  public CaseIsHandledVo selectCaseIsHandledPageName(Long cId, String caseType) {
    return caseIsHandledMapper.selectCaseIsHandledPageName(cId, caseType);
  }

  /**
   * 根据案件ID 警报事件ID 设备ID 展示案件详情页
   *
   * @param wid 警报事件ID
   * @param cid 根据案件ID
   * @param did 设备ID
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public CaseDetails selectCaseDetailsById(Long wid, Long cid, Long did) {
    Device device = deviceMapper.selectById(did);
    Case aCase = caseMapper.getById(cid);
    WarnEvent warnEvent = warnEventMapper.selectById(wid);
    UserInfo userInfo1 = userInfoMapper.selectById(warnEvent.getReportUserInfoId());
    Receipt receipt = receiptMapper.getById(cid);
    UserInfo userInfo2 = userInfoMapper.selectById(receipt.getReceiptUserInfoId());
    File file1 = fileMapper.selectByWid(wid);
    File file2 = fileMapper.selectByCid(cid);
    CaseDetails caseDetails = new CaseDetails();
    caseDetails
        .setCid(cid)
        .setWid(wid)
        .setDCode(device.getCode())
        .setDataOrigin(warnEvent.getDataOrigin())
        .setGeomDes(aCase.getLocation())
        .setReason(warnEvent.getType())
        .setUsername(userInfo1.getUsername())
        .setCreateTime(warnEvent.getCreateTime())
        .setRemark(warnEvent.getRemark())
        .setLevel(aCase.getGrade())
        .setCaseDescribe(aCase.getCaseDescribe())
        .setAdvice(aCase.getAdvice()) .setName(userInfo2.getUsername())
            .setMatter(warnEvent.getReason())
            .setContext(receipt.getContext());
    if(Objects.nonNull(file1)){
        caseDetails.setBeforeLink(file1.getLink());
    }
    if(Objects.nonNull(file2)) {
        caseDetails.setAfterLink(file2.getLink());
    }
    caseDetails.setUpdateTime(receipt.getUpdateTime());
    return caseDetails;
  }


  @Override
  public int deleteCaseIsHanledByIds(List idList) {
    return caseMapper.removeByIds(idList);
  }

  /** 井盖案件管理 导出未处理的案件数据 */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void exportNoHandleToExcel(HttpServletResponse response, String warnType) {
    List<CaseNoHandle> caseNoHandles = caseManagementMapper.importNoHandleToExcel(warnType);

    Set<String> exclude = new HashSet<>();
    exclude.add("id");
    exclude.add("wid");
    exclude.add("deviceKey");
    exclude.add("cid");
    exclude.add("level");
    exclude.add("caseDescribe");
    exclude.add("advice");
    exclude.add("link");
    exclude.add("originName");
    exclude.add("remark");
    exclude.add("name");
    ExcelUtil.objectToExcelAndDownload(
        response, exclude, "noHandle", CaseNoHandle.class, caseNoHandles);
  }

  /** 井盖案件管理 导出处理中的案件数据 */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void exportHandlingToExcel(
      HttpServletResponse response, String caseType, String warnType) {
    List<CaseNoHandle> caseNoHandles =
        caseManagementMapper.selectCaseHandlingPage(caseType, warnType);
    Set<String> exclude = new HashSet<>();
    exclude.add("id");
    exclude.add("wid");
    exclude.add("deviceKey");
    exclude.add("cid");
    exclude.add("link");
    exclude.add("name");
    ExcelUtil.objectToExcelAndDownload(
        response, exclude, "casehandling", CaseNoHandle.class, caseNoHandles);
  }

  /** 一路一档案件管理,导出案件在未派单时的数据 */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void exportOneWayNoHandle(HttpServletResponse response, String caseType) {
    List<OneWayCaseNoHandVo> records = oneWayCaseMapper.selectInspectionPage(caseType);
    FacilityCodeTurnToLocation(records);
    Set<String> exclude = new HashSet<>();
    exclude.add("id");
    exclude.add("iid");
    exclude.add("link");
    exclude.add("updateTime");
    ExcelUtil.objectToExcelAndDownload(
        response, exclude, "OneWayCaseNoHand", OneWayCaseNoHandVo.class, records);
  }
  /** 一路一档案件管理 导出已经处理的数据 分页查询 */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void exportOneWayIsHandled(HttpServletResponse response, String caseType) {
    List<OneWayCaseNoHandVo> records = oneWayCaseMapper.selectInspectionCaseIsHandledPage(caseType);
    FacilityCodeTurnToLocation(records);
    Set<String> exclude = new HashSet<>();
    exclude.add("id");
    exclude.add("iid");
    exclude.add("link");
    ExcelUtil.objectToExcelAndDownload(
        response, exclude, "OneWayCaseIsHandled", OneWayCaseNoHandVo.class, records);
  }

  // 泵站，查询数据管理泵站运行时数据的分页查询
  @Override
  public Page<PumpOperatingDataVo> PumpOperatingDataVo(Page<PumpOperatingDataVo> page) {
    return pumpStationDataManagementMapper.selectPumpOperatingData(page);
  }

  // 泵站，导出数据管理泵站运行时的数据
  @Override
  public List<PumpOperatingDataVo> exportPumpOperatingData() {
    return pumpStationDataManagementMapper.selectPumpOperatingData();
  }

  // 泵站，查询数据管理液位监测时的数据
  @Override
  public Page<PumpOperatingDataVo> selectPumpPolingCheckPage(Page<PumpOperatingDataVo> page) {
    return pumpStationDataManagementMapper.selectPumpPolingCheckPage(page);
  }

  @Override
  public List<CaseNoHandle> mobileNewTest(String caseType, String warnType) {
    return caseManagementMapper.mobileNewTest(caseType, warnType);
  }

  /** 一路一档案件管理 案件派单 */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public ResponseVo OneWaySendCase(OneWaySendCase oneWaySendCase) throws IOException {
    // 发送任务短信
    caseService.insertMessageToDepartment(
        ConstantUtil.MODULE_NAME.WAY, "案件处理任务", "领取任务", wayDepartmentName);
    Case aCase = new Case();
    aCase.setId(oneWaySendCase.getCid());
    aCase.setStatus("新任务");
    aCase.setGrade(oneWaySendCase.getGrade());
    aCase.setCaseDescribe(oneWaySendCase.getCaseDescribe());
    aCase.setAdvice(oneWaySendCase.getAdvice());
    InspectionEvent inspectionEvent = inspectionEventMapper.selectById(oneWaySendCase.getIid());
    inspectionEvent.setSendOrder(true);
    inspectionEventMapper.updateById(inspectionEvent);
    caseMapper.updateOneWayCase(aCase);
    return getInsertFileResult(oneWaySendCase) > 0 ? ResponseVo.SUCCESS : ResponseVo.SERVER_ERROR;
  }

  // 泵站案件管理 查询在未派单时的分页查询
  @Override
  public Page<CaseNoHandle> selectPumpCaseNoHandlePage(
      Page<CaseNoHandle> page,
      String dataOrigin,
      String reason,
      String username,
      String startTimestamp,
      String endTimestamp,
      String warnType) {
    return caseManagementMapper.selectPumpCaseNoHandlePage(
        page, dataOrigin, reason, username, startTimestamp, endTimestamp, warnType);
  }

  // 泵站案件管理 查询案件在处理中的分页查询
  @Override
  public Page<CaseNoHandle> selectPumpCaseHandlingPage(
      Page<CaseNoHandle> page,
      String dataOrigin,
      String reason,
      String username,
      String startTimestamp,
      String endTimestamp,
      String caseType,
      String warnType) {
    Page<CaseNoHandle> caseHandlingPage =
        caseManagementMapper.selectPumpCaseHandlingPage(
            page, dataOrigin, reason, username, startTimestamp, endTimestamp, caseType, warnType);
    List<CaseNoHandle> records = caseHandlingPage.getRecords();
    selectLinkAndName(records);
    return caseHandlingPage;
  }

  // 泵站案件管理 查询案件在已处理的分页查询
  @Override
  public Page<CaseIsHandledVo> selectPumpCaseIsHandledPage(
      Page<CaseIsHandledVo> page,
      String dataOrigin,
      String reason,
      String username,
      String startTimestamp,
      String endTimestamp,
      String caseType,
      String warnType) {
    return caseIsHandledMapper.selectPumpCaseIsHandledPage(
        page, dataOrigin, reason, username, startTimestamp, endTimestamp, caseType, warnType);
  }

  // 泵站数据管理 导出有害气体检测的数据
  @Override
  public List<NoxiousGasVo> exportPumpNoxiousGasData() {
    return pumpStationDataManagementMapper.selectPumpNoxiousGasData();
  }

  // 封装一路一档案件管理中根据问题桥梁或道路的code查询问题桥梁或道路所在的位置
  private void FacilityCodeTurnToLocation(List<OneWayCaseNoHandVo> records) {
    for (OneWayCaseNoHandVo record : records) {
      String facilityId = record.getFacilityId();
      if (facilityId.startsWith("Q")) {
        QueryWrapper<BridgeGis> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", facilityId);
        record.setFacilityId(bridgeGisMapper.selectOne(queryWrapper).getName());
      } else {
        QueryWrapper<RoadGis> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", facilityId);
        record.setFacilityId(roadGisMapper.selectOne(queryWrapper).getName());
      }
    }
  }

  private int getInsertFileResult(OneWaySendCase oneWaySendCase) throws IOException {
    if (oneWaySendCase.getFile() != null) {
      File file = getFilePo(null, moduleName, oneWaySendCase.getFile());
      if (fileMapper.insert(file) > 0) {
        Long fid = file.getId();
        InspectionEventFileMapping inspectionEventFileMapping = new InspectionEventFileMapping();
        inspectionEventFileMapping.setFileId(fid);
        inspectionEventFileMapping.setInspectionEventId(oneWaySendCase.getIid());
        inspectionEventFileMapping.setCreateTime(timeFormat(System.currentTimeMillis()));
        inspectionEventFileMapping.setUpdateTime(timeFormat(System.currentTimeMillis()));
        return inspectionEventFileMappingMapper.insert(inspectionEventFileMapping);
      }
    }
    return 0;
  }

  /** 一路一档案件管理，查询案件在处理中的分页查询 */
  @Override
  public Page<CaseNoHandle> selectCaseHandlingPage(
      Page<CaseNoHandle> page,
      String caseType,
      String warnType,
      String dataOrigin,
      String deviceCode,
      String reason,
      String username,
      String startTimestamp,
      String endTimestamp) {

    Page<CaseNoHandle> handlingCasePage =
        caseManagementMapper.selectCaseHandlingPage(
            page,
            caseType,
            warnType,
            dataOrigin,
            deviceCode,
            reason,
            username,
            startTimestamp,
            endTimestamp);
    List<CaseNoHandle> records = handlingCasePage.getRecords();
    selectLinkAndName(records);
    return handlingCasePage;
  }

  @Override
  public CaseTrackVo selectCaseTrack(Long id) {
    CaseTrackVo caseTrackVo = caseTrackMapper.selectCaseTrack(id);
    File file = fileMapper.selectByCid(id);
    if (file != null) {
      caseTrackVo.setAfterLink(file.getLink());
    }
    File file1 = fileMapper.selectByWid(caseTrackVo.getWid());
    if (file1 != null) {
      caseTrackVo.setBeforeLink(file1.getLink());
    }
    return caseTrackVo;
  }

  @Override
  public int deleteCaseIsHanled(Long id) {
    return caseMapper.deleteById(id);
  }

  /** 井盖案件管理 导出已处理的案件数据 */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void exportIsHandledToExcel(
      HttpServletResponse response, String caseType, String warnType) {
    List<CaseIsHandledVo> isHandledVos =
        caseIsHandledMapper.selectCaseIsHandledPage(
            caseType, warnType, null, null, null, null, null, null);
    for (CaseIsHandledVo record : isHandledVos) {
      CaseIsHandledVo handledPageName =
          caseIsHandledMapper.selectCaseIsHandledPageName(record.getCid(), caseType);
      record.setName(handledPageName.getName());
    }
    Set<String> exclude = new HashSet<>();
    exclude.add("cid");
    exclude.add("id");
    exclude.add("wid");
    exclude.add("did");
    exclude.add("name");
    ExcelUtil.objectToExcelAndDownload(
        response, exclude, "caseIsHandled", CaseIsHandledVo.class, isHandledVos);
  }

  /** 一路一档案件管理 查询案件在未派单时的分页查询 */
  @Override
  public Page<OneWayCaseNoHandVo> selectInspectionPage(
      Page<OneWayCaseNoHandVo> page,
      String caseType,
      String dataOrigin,
      String reason,
      String name,
      String startTimestamp,
      String endTimestamp) {
    Page<OneWayCaseNoHandVo> oneWayCaseNoHandVoPage =
        oneWayCaseMapper.selectInspectionPage(
            page, caseType, dataOrigin, reason, name, startTimestamp, endTimestamp);
    List<OneWayCaseNoHandVo> records = oneWayCaseNoHandVoPage.getRecords();
    FacilityCodeTurnToLocation(records);
    return oneWayCaseNoHandVoPage;
  }

  /** 一路一档案件管理 案件新建 */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public long insertCaseAndInspection(NewCase newCase) throws IOException {

    // 新建案件
    Case c = new Case();
    // 前台获取
    c.setGrade(newCase.getGrade());
    c.setLocation(newCase.getLocation());
    c.setCaseDescribe(newCase.getCaseDescribe());
    c.setAdvice(newCase.getAdvice());
    // c.setCaseType(newCase.getCaseType());
    // 后台默认
    c.setType("巡检案件");
    c.setStatus("新任务");

    c.setCreateTime(timeFormat(System.currentTimeMillis()));
    c.setUpdateTime(timeFormat(System.currentTimeMillis()));

    // 新建巡检事件
    InspectionEvent inspectionEvent = new InspectionEvent();
    // 前台获取
    if (newCase.getCreateTime() == null) {
      inspectionEvent.setCreateTime(timeFormat(System.currentTimeMillis()));
    } else {
      inspectionEvent.setCreateTime(newCase.getCreateTime());
    }
    // 发送任务短信
    caseService.insertMessageToDepartment(
        ConstantUtil.MODULE_NAME.WAY, "案件处理任务", "领取任务", wayDepartmentName);
    inspectionEvent.setReason(newCase.getReason());
    inspectionEvent.setReportUserInfoId(newCase.getReportUserInfoId());
    inspectionEvent.setSendOrder(true);
    inspectionEvent.setRemark(newCase.getRemark());
    inspectionEvent.setLevel(newCase.getGrade());
    inspectionEvent.setFacilityId(newCase.getGeometry());
    //        if (newCase.getGeometry()!=null){
    //            inspectionEvent.setGeometry(newCase.getGeometry());
    //        }
    // 后台默认
    inspectionEvent.setReset("否");
    inspectionEvent.setDataOrigin("人工上报");
    inspectionEvent.setType("巡检事件");
    inspectionEvent.setCreateTime(timeFormat(System.currentTimeMillis()));
    inspectionEvent.setUpdateTime(timeFormat(System.currentTimeMillis()));
    Long cid = null;
    Long iid = null;
    if (caseMapper.insertCase(c) > 0) {
      cid = c.getId();
      if (inspectionEventMapper.insert(inspectionEvent) > 0) {
        iid = inspectionEvent.getId();
        // 新建巡检事件与案件关联
        CaseInspectionEventMapping caseInspectionEventMapping = new CaseInspectionEventMapping();
        caseInspectionEventMapping.setCaseId(cid);
        caseInspectionEventMapping.setInspectionEventId(iid);
        caseInspectionEventMapping.setCreateTime(timeFormat(System.currentTimeMillis()));
        caseInspectionEventMapping.setUpdateTime(timeFormat(System.currentTimeMillis()));
        caseInspectionEventMappingMapper.insert(caseInspectionEventMapping);
        return iid;
      }
    }
    return 0;
  }

  /** 一路一档案件管理 查询案件在处理中的分页查询 */
  @Override
  public Page<OneWayCaseNoHandVo> selectInspectionCaseHandingPage(
      Page<OneWayCaseNoHandVo> page,
      String caseType,
      String dataOrigin,
      String reason,
      String name,
      String startTimestamp,
      String endTimestamp) {
    Page<OneWayCaseNoHandVo> oneWayCaseNoHandVoPage =
        oneWayCaseMapper.selectInspectionCaseHandingPage(
            page, caseType, dataOrigin, reason, name, startTimestamp, endTimestamp);
    List<OneWayCaseNoHandVo> records = oneWayCaseNoHandVoPage.getRecords();
    // 根据问题道路或桥梁的编码，查询问题道路或桥梁的位置
    FacilityCodeTurnToLocation(records);
    return oneWayCaseNoHandVoPage;
  }

  /** 一路一档案件管理 重新派单 */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public ResponseVo OneWayRepeatSendCase(OneWaySendCase oneWaySendCase) throws IOException {
    // 把原本的案件进行逻辑删除
    Case ca = new Case();
    ca.setId(oneWaySendCase.getCid());
    ca.setStatus("案件隐藏");
    caseMapper.updateCaseById(ca);
    // 新建案件进行管理
    Case aCase = new Case();
    aCase.setType("巡检案件");
    aCase.setStatus("新任务");
    aCase.setGrade(oneWaySendCase.getGrade());
    aCase.setCaseDescribe(oneWaySendCase.getCaseDescribe());
    aCase.setAdvice(oneWaySendCase.getAdvice());
    aCase.setCreateTime(timeFormat(System.currentTimeMillis()));
    aCase.setUpdateTime(timeFormat(System.currentTimeMillis()));
    Long cid = null;
    if (caseMapper.insertCase(aCase) > 0) {
      cid = aCase.getId();
    }
    // 删除警告文件关联表
    QueryWrapper<InspectionEventFileMapping> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("inspection_event_id", oneWaySendCase.getIid());
    List<InspectionEventFileMapping> list =
        inspectionEventFileMappingMapper.selectList(queryWrapper);
    for (InspectionEventFileMapping inspectionEventFileMapping : list) {
      inspectionEventFileMappingMapper.deleteById(inspectionEventFileMapping.getId());
    }
    // 发送任务短信
    caseService.insertMessageToDepartment(
        ConstantUtil.MODULE_NAME.WAY, "巡检案件任务", "领取任务", wayDepartmentName);
    // 新建案件与巡检事件关联
    CaseInspectionEventMapping caseInspectionEventMapping = new CaseInspectionEventMapping();
    caseInspectionEventMapping.setCaseId(cid);
    caseInspectionEventMapping.setInspectionEventId(oneWaySendCase.getIid());
    caseInspectionEventMapping.setCreateTime(timeFormat(System.currentTimeMillis()));
    caseInspectionEventMapping.setUpdateTime(timeFormat(System.currentTimeMillis()));
    caseInspectionEventMappingMapper.insert(caseInspectionEventMapping);
    return ResponseVo.successWithData(oneWaySendCase.getIid());
  }

  /**
   * 一路一档案件管理 案件追踪，需要传入当前案件的 cid
   *
   * @return 前案件的 cid
   */
  @Override
  public CaseTrackVo selectOneWayCaseTrack(Long id) {
    CaseTrackVo caseTrackVo = caseTrackMapper.selectOneWayCaseTrack(id);
    if (Objects.isNull(caseTrackVo)){
        return null;
    }
    File file = fileMapper.selectByCid(id);
    if (file != null) {
      caseTrackVo.setAfterLink(file.getLink());
    }
    File file1 = fileMapper.selectInspectionFile(caseTrackVo.getIid());
    if (file1 != null) {
      caseTrackVo.setBeforeLink(file1.getLink());
    }
    return caseTrackVo;
  }

  /** 一路一档案件管理,导出案件在处理时的数据 */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void exportOneWayHandling(HttpServletResponse response, String caseType) {
    List<OneWayCaseNoHandVo> records = oneWayCaseMapper.selectInspectionCaseHandingPage(caseType);
    FacilityCodeTurnToLocation(records);
    Set<String> exclude = new HashSet<>();
    exclude.add("id");
    exclude.add("iid");
    exclude.add("link");
    exclude.add("updateTime");

    ExcelUtil.objectToExcelAndDownload(
        response, exclude, "OneWayCaseHanding", OneWayCaseNoHandVo.class, records);
  }

  /** 一路一档案件管理 查询案件在已经处理的数据 分页查询 */
  @Override
  public Page<OneWayCaseNoHandVo> selectInspectionCaseIsHandledPage(
      Page<OneWayCaseNoHandVo> page,
      String caseType,
      String dataOrigin,
      String reason,
      String name,
      String startTimestamp,
      String endTimestamp) {
    Page<OneWayCaseNoHandVo> oneWayCaseNoHandVoPage =
        oneWayCaseMapper.selectInspectionCaseIsHandledPage(
            page, caseType, dataOrigin, reason, name, startTimestamp, endTimestamp);
    List<OneWayCaseNoHandVo> records = oneWayCaseNoHandVoPage.getRecords();
    // 根据问题道路或桥梁的编码，查询问题道路或桥梁的位置
    FacilityCodeTurnToLocation(records);
    formatOneWayCaseNoHandVo(records);
    return oneWayCaseNoHandVoPage;
  }

  // 泵站，导出数据管理液位监测时的数据
  @Override
  public List<PumpOperatingDataVo> exportPumpPolingCheckPage() {
    return pumpStationDataManagementMapper.selectPumpPolingCheckPage();
  }

  @Override
  public List<OneWayCaseNoHandVo> selectInspectionNewTest(String caseType) {
    List<OneWayCaseNoHandVo> oneWayCaseNoHandVos = oneWayCaseMapper.selectInspectionNewTest(caseType);
    formatOneWayCaseNoHandVo(oneWayCaseNoHandVos);
    return oneWayCaseNoHandVos;
  }

  @Override
  public Page<OneWayCaseNoHandVo> selectInspectionCaseOnlyHandingPage(
      Page<OneWayCaseNoHandVo> page, String caseType) {
    Page<OneWayCaseNoHandVo> oneWayCaseNoHandVoPage = oneWayCaseMapper.selectInspectionCaseOnlyHandingPage(page, caseType);
    formatOneWayCaseNoHandVo(oneWayCaseNoHandVoPage.getRecords());
    return oneWayCaseNoHandVoPage;
  }

  @Override
  public void formatOneWayCaseNoHandVo(List<OneWayCaseNoHandVo> records){
    for(OneWayCaseNoHandVo vo:records){
      QueryWrapper<InspectionEventFileMapping> queryWrapper = new QueryWrapper<>();
      queryWrapper.eq("inspection_event_id",vo.getIid());
      List<InspectionEventFileMapping> inspectionEventFileMappings = inspectionEventFileMappingMapper.selectList(queryWrapper);
      if(Objects.nonNull(inspectionEventFileMappings)&&!inspectionEventFileMappings.isEmpty()){
        vo.setLink(fileMapper.selectById(inspectionEventFileMappings.get(0).getFileId()).getLink());
      }
    }
  }

  /** 一路一档案 派单，重新派单，新建案件多文件上传 */
  @Override
  public ResponseVo getInsertFileResult(long iid, MultipartFile file1, String moduleName)
      throws IOException {
    if (file1 != null) {
      File file = getFilePo(null, moduleName, file1);
      if (fileMapper.insert(file) > 0) {
        Long fid = file.getId();
        InspectionEventFileMapping inspectionEventFileMapping = new InspectionEventFileMapping();
        inspectionEventFileMapping.setFileId(fid);
        inspectionEventFileMapping.setInspectionEventId(iid);
        inspectionEventFileMapping.setCreateTime(timeFormat(System.currentTimeMillis()));
        inspectionEventFileMapping.setUpdateTime(timeFormat(System.currentTimeMillis()));
        int insert = inspectionEventFileMappingMapper.insert(inspectionEventFileMapping);
        return insert > 0 ? ResponseVo.SUCCESS : ResponseVo.SERVER_ERROR;
      }
    }
    return ResponseVo.SUCCESS;
  }

  // 一路一档案件管理 已经处理的数据 案件详情
  @Override
  @Transactional(rollbackFor = Exception.class)
  public OneWayCaseDetailsVo selectOneWayCaseDetails(Long iid, Long cid) {
    OneWayCaseDetailsVo1 oneWayCaseDetailsVo1 =
        oneWayCaseDetails1Mapper.selectOneWayCaseDetails1(iid);
    File file = fileMapper.selectInspectionFile(iid);
    if (file != null) {
      oneWayCaseDetailsVo1.setBeforeLink(file.getLink());
    }

    OneWayCaseDetailsVo2 oneWayCaseDetailsVo2 =
        oneWayCaseDetails2Mapper.selectOneWayCaseDetails2(cid);
    File file1 = fileMapper.selectByCid(cid);
    if (file1 != null) {
      oneWayCaseDetailsVo2.setAfterLink(file1.getLink());
    }
    OneWayCaseDetailsVo oneWayCaseDetailsVo = new OneWayCaseDetailsVo();
    oneWayCaseDetailsVo.setOneWayCaseDetailsVo1(oneWayCaseDetailsVo1);
    oneWayCaseDetailsVo.setOneWayCaseDetailsVo2(oneWayCaseDetailsVo2);
    return oneWayCaseDetailsVo;
  }

  // 泵站数据管理 查询有害气体检测的分页查询
  @Override
  public Page<NoxiousGasVo> selectPumpNoxiousGasData(Page<NoxiousGasVo> page) {
    return pumpStationDataManagementMapper.selectPumpNoxiousGasData(page);
  }

  // 封装案件管理中处理中与已处理中回执文件中的fileName，link
  private void selectLinkAndName(List<CaseNoHandle> records) {
    for (CaseNoHandle caseNoHandle : records) {
      // 查询相关file
      Map<String, String> fileByWarnId =
          caseManagementMapper.findFileByWarnId(caseNoHandle.getWid());
      if (Objects.isNull(fileByWarnId)) {
        continue;
      }
      caseNoHandle.setOriginName(fileByWarnId.getOrDefault("fileName", null));
      caseNoHandle.setLink(fileByWarnId.getOrDefault("link", null));
    }
  }
}
